package com.acme.bankapp.domine.client;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import com.acme.bankapp.domine.account.Account;

@SuppressWarnings("serial")
public class Client implements Serializable {
    private Gender gender;
    private String name;
    private List<Account> accounts = new ArrayList<Account>();

    public List<Account> getAccounts() {
        return Collections.unmodifiableList(accounts);
    }

    public Client(final String name, final Gender gender) {
        this.name = name;
        this.gender = gender;
    }

    public String getClientSalutation() {
        return gender.toString() + " " + name;
    }

    public String getName() {
        return name;
    }

    public void addAccount(final Account account) {
        accounts.add(account);
    }

    public Account getAccount(final int id) {
        for (Account account : accounts) {
            if (account.getId() == id) {
                return account;
            }
        }
        return null;
    }

    @Override
    public String toString() {
        StringBuffer clientWithAccountsString = new StringBuffer("Client "
            + getClientSalutation() + "\n  accounts:\n");
        for (Account account : accounts) {
            clientWithAccountsString.append("    ");
            clientWithAccountsString.append(account);
            clientWithAccountsString.append("\n");
        }
        return clientWithAccountsString.toString();
    }

    @Override
    public boolean equals(final Object o) {
        // Comparison of business keys (name, gender) is enough
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }

        Client client = (Client) o;

        if (gender != client.gender) {
            return false;
        }
        if (name != null ? !name.equals(client.name) : client.name != null) {
            return false;
        }

        return true;
    }

    @Override
    public int hashCode() {
        int result = gender != null ? gender.hashCode() : 0;
        result = 31 * result + (name != null ? name.hashCode() : 0);
        return result;
    }

    public Account getAccountById(final int id) {
        for (Account account : accounts) {
            if (account.getId() == id) {
                return account;
            }
        }
        return null;
    }
}
